package util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

public class BaseDao {
    private static String driver;
    private static String url;
    private static String userName;
    private static String passWord;
    private static BaseDao baseDao=null;

    private BaseDao() {
        Properties properties = new Properties();
        InputStream stream = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(stream);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            userName = properties.getProperty("userName");
            passWord = properties.getProperty("passWord");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //单列

    private static BaseDao getInstance(){
        if (baseDao!=null){
            return baseDao;
        }
        return new BaseDao();
    }

    public static PreparedStatement getPs(String sql){
        getInstance();
        PreparedStatement ps=null;
        try {
            Class.forName(driver);
            Connection connection = DriverManager.getConnection(url, userName, passWord);
            ps = connection.prepareStatement(sql);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
        }
        return ps;
    }



    public static void close(AutoCloseable...args){
        if (args!=null){
            for (AutoCloseable arg : args) {
                try {
                    arg.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
